package com.bbird.od.finance.service.domain;

import com.alibaba.excel.EasyExcel;
import com.bbird.od.finance.service.models.BankFlow;
import com.bbird.od.finance.service.models.DYBankFLow;
import com.bbird.od.finance.service.models.ReconciliationResult;
import com.bbird.od.finance.service.models.type.BankType;
import com.bbird.od.finance.service.listener.FlowExcelListener;

import java.io.File;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * @author ziyang Kuang
 * @date 2021/4/18
 * @describe
 */
public class DYReconciliationHandler extends AbstractReconciliationHandler<DYBankFLow> {
    /**
     * 反向对账（检查预收）
     */
    @Override
    protected void bankToErpCheck(List<DYBankFLow> bankFlows) {
        Map<String, ReconciliationResult> reconciliationResultMap = reconciliationResultsMapThreadLocal.get();
        bankFlows.forEach(bankFlow -> {
            BankFlow bankFlowSuper = (BankFlow) bankFlow;
            String homeOrderNumber = bankFlowSuper.getHomeOrderNumber();
            ReconciliationResult result = reconciliationResultMap.get(homeOrderNumber);
            if (result == null) {
                // 预收款
                result = new ReconciliationResult();
                result.setHomeOrderNumber(homeOrderNumber);
                reconciliationResultMap.put(homeOrderNumber, result);
            }

            BigDecimal amount = bankFlowSuper.getActualAmount();
            BigDecimal refundAmount = bankFlow.getRefundAmount();
            // 设置收货款;
            result.setActualReceivableGoodsAmount(result.getActualReceivableGoodsAmount().add(amount));
            // 设置退货款
            if (refundAmount.compareTo(BigDecimal.ZERO) < 0) {
                result.setRefundReceivableGoodsAmount(result.getRefundReceivableGoodsAmount().add(refundAmount));
            }
            result.setReceivedAmount(result.getReceivedAmount().add(amount));
        });
    }

//    @Override
//    protected List<ERPFlow> analyseErpFlow(File erpFlowExcel) {
//        List<ERPFlow> erpFlows = super.analyseErpFlow(erpFlowExcel);
//        // ERP对账单订单号尾部
//        erpFlows.stream().forEach(erpFlow -> {
//            String homeOrderNumber = erpFlow.getHomeOrderNumber().replaceAll("A", "");
//            erpFlow.setHomeOrderNumber(homeOrderNumber);
//        });
//        return erpFlows;
//    }

    @Override
    List<DYBankFLow> analyseBankFlow(File bankFlowExcel) {
        FlowExcelListener<DYBankFLow> listener = new FlowExcelListener(this.getBankType(), bankFlowExcel.getName());
        EasyExcel.read(bankFlowExcel, DYBankFLow.class, listener).headRowNumber(1).sheet().doRead();
        listener.getDataList().forEach(item->{
            item.setOrderNumber(item.getOrderNumber().replaceAll("['|’]", "")+"A");
        });
        return listener.getDataList();
    }

    @Override
    BankType getBankType() {
        return BankType.DY;
    }
}
